package com.example.demo.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.util.Map;

public class JsonUtil {

    public static String readFromFile(String fileName) {
        String jsonStr = "";
        try{
            File jsonFile = new File(fileName);
            FileReader fileReader = new FileReader(jsonFile);
            Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
            int ch = 0;
            StringBuffer sb = new StringBuffer();
            while ((ch = reader.read()) != -1) {
                sb.append((char) ch);
            }
            fileReader.close();
            reader.close();
            jsonStr = sb.toString();
            return jsonStr;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 写入json文件
     * @param jsonPath json文件路径
     * @param dataMap 数据map
     */
    public static void writeToJsonFile(String jsonPath, Map<String, Object> dataMap) throws Exception {
        String data = new JSONObject(dataMap).toJSONString();
        File jsonFile = new File(jsonPath);
        OutputStreamWriter writer = null;
        BufferedWriter bw = null;
        try {
            if (!jsonFile.exists()) {
                File fileParent = jsonFile.getParentFile();
                if (!fileParent.exists()) {
                    fileParent.mkdirs();
                }
                jsonFile.createNewFile();
            }
            writer = new OutputStreamWriter(new FileOutputStream(jsonFile), "utf-8");
            bw = new BufferedWriter(writer);
            bw.write(data);
        } finally {
            if (bw != null) {
                bw.close();
            }
            if (writer != null) {
                writer.close();
            }
        }
    }

    public static <T> T parseObject(String s, Class<T> clazz) {
        try{
            T t = JSON.parseObject(s, clazz);
            return t;
        } catch (Exception e) {
            throw e;
        }
    }

    public static <T> T readObjectFromFile(String fileName, Class<T> clazz) {
        String s = readFromFile(fileName);
        T t = parseObject(s, clazz);
        return t;
    }

    public static <T> T mapToObject(Map map, Class<T> clazz) {
        String jsonStr = JSONObject.toJSONString(map);
        return parseObject(jsonStr, clazz);
    }
}
